/**
 * Created by lxl on 2015/11/4.
 */


var host = "http://localhost:8080/ssms/" ;

var views = "http://localhost:8080/views/" ;

var courseInfoDo_list;
var selectedCourseInfoDo;
var student_list_table;
var student_list;

function getCookie( name ){

    var arr = document.cookie.split(";") ;

    for( var  i = 0 ; i < arr.length ; i++){

        if( arr[i].split("=")[0] == name ){

            return arr[i].split("=")[1] ;
        }
    }
}

function sendPost( data , url , callback ){


    if (window.XMLHttpRequest)
    {// code for IE7+, Firefox, Chrome, Opera, Safari
        window.jsonHttp=new XMLHttpRequest();
    }
    else
    {// code for IE6, IE5
        window.jsonHttp=new ActiveXObject("Microsoft.XMLHTTP");
    }

    window.jsonHttp.onreadystatechange=callback ;

    window.jsonHttp.open("POST",host + url ,true) ;
    window.jsonHttp.setRequestHeader("Content-type","application/json");
    window.jsonHttp.setRequestHeader("token",getCookie("token")) ;
    window.jsonHttp.send(data) ;


}

function login(){

    var username = document.login_form.username.value ;
    var password = document.login_form.password.value ;

    var  data = {} ;

    data.username = username ;
    data.password = password ;

    data = JSON.stringify(data) ;

    sendPost( data , "login" , loginCallBack ) ;

}

function loginCallBack(){

    if ( window.jsonHttp.readyState==4 && window.jsonHttp.status==200) {

        try{
            var result = JSON.parse(window.jsonHttp.responseText);

            if (result.succes == true) {

                document.cookie = "token=" + result.param.token;

                window.open(views + "index.html", "_self");

            } else {

                alert(result.error);

            }

        }catch(e) {


        }

    }
}

function addRightPage( url  , callback ){

    if (window.XMLHttpRequest)
    {// code for IE7+, Firefox, Chrome, Opera, Safari
        window.jsonHttp=new XMLHttpRequest();
    }
    else
    {// code for IE6, IE5
        window.jsonHttp=new ActiveXObject("Microsoft.XMLHTTP");
    }

    window.jsonHttp.onreadystatechange=function(){

        if (window.jsonHttp.readyState==4 && jsonHttp.status==200)
        {


            if( callback != null ){

                window.leftPge = jsonHttp.responseText ;
                callback() ;

            }else{

                document.getElementById("left_page").innerHTML = jsonHttp.responseText;

            }

        }
    }

    window.jsonHttp.open("GET",views + url ,true) ;
    window.jsonHttp.send() ;

}

function addUser(){

    var username = document.add_user_form.username.value ;
    var name = document.add_user_form.name.value ;
    var level = document.add_user_form.level.value ;

    if( username == "" ){

        alert("学号/工号不能為空") ;

        return ;

    }
    if(  name == ""  ){

        alert("姓名不能為空") ;

        return ;

    }

    var  data = {} ;

    data.username = username ;
    data.name = name ;
    data.level = level ;

    data = JSON.stringify(data) ;

    sendPost(data,"add/user",addUserCallBack ) ;

}

function addUserCallBack(){

    if (window.jsonHttp.readyState==4 && jsonHttp.status==200)
    {

        var result ;

        try{

            result = JSON.parse(window.jsonHttp.responseText);

            if( result.succes == true ){

                alert("添加用户成功") ;
                addRightPage('user_table.html',showUserTable ) ;

            }else{

                alert(result.error) ;

            }

        }catch (e){

        }

    }

}

function addCourese(){

    var name = document.add_course_form.name.value ;
    var gp = document.add_course_form.gp.value ;
    var teacherId = document.add_course_form.teacher.value ;

    if( name == ""){

        alert("课程名不能为空") ;

        return ;

    }

    var data = {} ;

    data.name = name ;
    data.gp = gp ;
    data.teacherId = teacherId ;

    data = JSON.stringify(data);

    sendPost(data,"add/course",addCourseCallBack) ;

}

function addCourseCallBack(){

    if (window.jsonHttp.readyState==4 && jsonHttp.status==200)
    {

        var result ;

        try{

            result = JSON.parse(window.jsonHttp.responseText);

            if( result.succes == true ){

                alert("添加课程成功") ;
                addRightPage('course_table.html',showCourseTable ) ;

            }else{

                alert(result.error) ;

            }

        }catch (e){

        }

    }

}

function showUserTable( ){

    sendPost(0,"query/user/list",showUserTableCallBack ) ;

}

function showUserTableCallBack(){

    if (window.jsonHttp.readyState==4 && jsonHttp.status==200)
    {

        var result ;

        try{

            result = JSON.parse(window.jsonHttp.responseText);

            if( result.succes == true ){

                document.getElementById("left_page").innerHTML = window.leftPge ;
                var table = document.getElementById("user_table") ;

                for( var  i = 0 ; i < result.param.user_list.length ;i++){

                    table.rows[i].cells[0].innerHTML = result.param.user_list[i].username ;
                    table.rows[i].cells[1].innerHTML = result.param.user_list[i].name ;

                    var level = result.param.user_list[i].level ;

                    if( level == "1" ){

                        level = "学生" ;

                    }else if( level == "2" ){

                        level = "教师"

                    }else if( level == "3"){

                        level = "管理员" ;

                    }


                    table.rows[i].cells[2].innerHTML = level ;

                }

            }else{

                alert(result.error) ;

            }

        }catch (e){

        }

    }

}

function showCourseTable(){

    sendPost(null , "query/course/list" ,showCourseTableCallBack ) ;

}

function showCourseTableCallBack(){

    if (window.jsonHttp.readyState==4 && jsonHttp.status==200) {

        var result;

        try {

            result = JSON.parse(window.jsonHttp.responseText);

            if (result.succes == true) {

                document.getElementById("left_page").innerHTML = window.leftPge;
                var table = document.getElementById("course_table");

                for( var  i = 0 ; i < result.param.course_list.length ; i++){

                    table.rows[i].cells[0].innerHTML = result.param.course_list[i].name ;
                    table.rows[i].cells[1].innerHTML = result.param.course_list[i].gp ;

                    for( var j = 0 ; j < result.param.user_list.length ; j++){

                        if( result.param.user_list[j].id == result.param.course_list[i].teacherId ){

                            table.rows[i].cells[2].innerHTML = result.param.user_list[j].name ;
                            break ;

                        }

                    }


                }

            } else {

                alert(result.error);

            }

        } catch (e) {

        }
    }

}

function showTeacherSelect(){

    sendPost( 2,"query/user/list",showTeacherSelectCallBack ) ;

}

function showTeacherSelectCallBack(){

    if (window.jsonHttp.readyState==4 && jsonHttp.status==200) {

        var result;

        try {

            result = JSON.parse(window.jsonHttp.responseText);

            if (result.succes == true) {

                document.getElementById("left_page").innerHTML = window.leftPge;
                var select = document.getElementById("teacher");

                for( var i = 0 ; i < result.param.user_list.length ; i++){

                    select.options.add( new Option( result.param.user_list[i].name , result.param.user_list[i].id)) ;

                }

            } else {

                alert(result.error);

            }

        } catch (e) {

        }
    }

}

function showTeacherCourseTable(){

    sendPost(null,"query/teacher/course",showTeacherCourseTableCallBack ) ;

}

function showTeacherCourseTableCallBack(){

    if (window.jsonHttp.readyState==4 && jsonHttp.status==200) {

        var result;

        try {

            result = JSON.parse(window.jsonHttp.responseText);

            if (result.succes == true) {

                document.getElementById("left_page").innerHTML = window.leftPge;
                var table = document.getElementById("course_table");

                for( var  i = 0 ; i < result.param.course_list.length ; i++){

                    table.rows[i].cells[0].innerHTML = result.param.course_list[i].name ;
                    table.rows[i].cells[1].innerHTML = result.param.course_list[i].gp ;
                    table.rows[i].cells[2].innerHTML = result.param.user_name ;

                }

                document.getElementById("course_table_add").style.display="none";

            } else {

                alert(result.error);

            }

        } catch (e) {

        }
    }

}

function showTeacherStudentTable(){

    sendPost(null,"query/student/course",showTeacherStudentTableCallBack ) ;

}

function showTeacherStudentTableCallBack(){

    if (window.jsonHttp.readyState==4 && jsonHttp.status==200) {

        var result;

        try {

            result = JSON.parse(window.jsonHttp.responseText);

            if (result.succes == true) {

                document.getElementById("left_page").innerHTML = window.leftPge;
                var table = document.getElementById("user_course_table");

                for( var  i = 0 ; i < result.param.course_list.length ; i++){

                    table.rows[i].cells[0].innerHTML = result.param.course_list[i].username ;
                    table.rows[i].cells[1].innerHTML = result.param.course_list[i].name ;
                    table.rows[i].cells[2].innerHTML = result.param.course_list[i].courseName ;

                    var overall = result.param.course_list[i].overall ;

                    if( overall == -1 ){

                        overall = "暂无" ;

                    }

                    table.rows[i].cells[3].innerHTML = overall  ;

                }

            } else {

                alert(result.error);

            }

        } catch (e) {

        }
    }

}

function showStudentCourseTable(){

    sendPost(null,"query/student/course/list",showStudentCourseTableCallBack) ;

}

function showStudentCourseTableCallBack(){

    if (window.jsonHttp.readyState==4 && jsonHttp.status==200) {

        var result;

        try {

            result = JSON.parse(window.jsonHttp.responseText);

            if (result.succes == true) {

                document.getElementById("left_page").innerHTML = window.leftPge;
                var table = document.getElementById("course_table");

                for( var  i = 0 ; i < result.param.course_list.length ; i++){

                    table.rows[i].cells[0].innerHTML = result.param.course_list[i].name ;
                    table.rows[i].cells[1].innerHTML = result.param.course_list[i].gp ;

                    for( var  j = 0 ; j < result.param.user_name.length ; j++){

                        if( result.param.user_name[j].id == result.param.course_list[i].id ){

                            table.rows[i].cells[2].innerHTML = result.param.user_name[j].name ;
                            break ;

                        }

                    }

                }

                document.getElementById("course_table_add").style.display="none";

            } else {

                alert(result.error);

            }

        } catch (e) {

        }
    }


}

function showStudentScoreTable(){

    sendPost(null,"query/score/list" ,showStudentScoreTableCallBack) ;

}

function showStudentScoreTableCallBack(){

    if (window.jsonHttp.readyState==4 && jsonHttp.status==200) {

        var result;

        try {

            result = JSON.parse(window.jsonHttp.responseText);

            if (result.succes == true) {

                document.getElementById("left_page").innerHTML = window.leftPge;
                var table = document.getElementById("score_table");

                for( var  i = 0 ; i < result.param.score_list.length ; i++){

                    table.rows[i].cells[1].innerHTML = result.param.score_list[i].performance ;
                    table.rows[i].cells[2].innerHTML = result.param.score_list[i].midterm ;
                    table.rows[i].cells[3].innerHTML = result.param.score_list[i].finals ;
                    table.rows[i].cells[4].innerHTML = result.param.score_list[i].overall ;

                    for( var  j = 0 ; j < result.param.course_list.length ; j++){

                        if( result.param.course_list[j].id == result.param.score_list[i].id ){

                            table.rows[i].cells[0].innerHTML = result.param.course_list[j].name ;
                            break ;

                        }

                    }

                }

            } else {

                alert(result.error);

            }

        } catch (e) {

        }
    }

}

function updatePassword(){

    var oldPassword = document.update_password_form.oldPassword.value ;
    var newPassword = document.update_password_form.newPassword.value ;
    var repeatPassword = document.update_password_form.repeatPassword.value ;


    if( oldPassword == ""){

        alert("旧密码不能为空") ;
        return ;

    }
    if( oldPassword == ""){

        alert("新密码不能为空") ;
        return ;

    }
    if( newPassword != repeatPassword ){

        alert("两次输入密码不一致") ;
        return ;

    }

    var data = {} ;

    data.password = newPassword ;
    data.oldPassword = oldPassword ;

    data = JSON.stringify(data) ;

    sendPost(data,"modify/password",updatePasswordCallBack) ;

}

function updatePasswordCallBack(){

    if (window.jsonHttp.readyState==4 && jsonHttp.status==200) {

        var result;

        try {

            result = JSON.parse(window.jsonHttp.responseText);

            if (result.succes == true) {

                alert("修改密码成功") ;
                document.cookie = "";
                window.open(views+"login.html", "_self") ;

            } else {

                alert(result.error);

            }

        } catch (e) {

        }
    }

}

function updateScoreTeacherSelect(){

    sendPost(null,"query/teacher/course",updateScoreTeacherSelectCallBack) ;

}

function updateScoreTeacherSelectCallBack(){

    if (window.jsonHttp.readyState==4 && jsonHttp.status==200) {

        var result;

        try {

            result = JSON.parse(window.jsonHttp.responseText);

            if (result.succes == true) {

                document.getElementById("left_page").innerHTML = window.leftPge;
                var select = document.getElementById("course_name");

                var sum = 0 ;

                for( var  i = 0 ; i < result.param.course_list.length ; i++){

                    select.options.add( new Option( result.param.course_list[i].name , result.param.course_list[i].id)) ;

                    sum++ ;
                }

                if( sum == 0 ){

                    select.options.add( new Option( "无" , "0")) ;


                }

                updateScoreStudentSelect() ;
            } else {

                alert(result.error);

            }

        } catch (e) {

        }
    }

}

function updateScoreStudentSelect(){

    sendPost(null,"query/student/course",updateScoreStudentSelectCallBack) ;

}

function updateScoreStudentSelectCallBack(){

    if (window.jsonHttp.readyState==4 && jsonHttp.status==200) {

        var result;

        try {

            result = JSON.parse(window.jsonHttp.responseText);

            if (result.succes == true) {

                var select = document.getElementById("student_name");

                select.innerHTML = "" ;

                var courseId = document.update_score_form.course_name.value ;

                var sum = 0 ;

                for( var  i = 0 ; i < result.param.course_list.length ; i++){

                    if( courseId == result.param.course_list[i].id ){

                        select.options.add( new Option( result.param.course_list[i].name , result.param.course_list[i].studentId)) ;

                        sum++ ;

                    }

                }

                if( sum == 0 ){

                    select.options.add( new Option( "无" , "0")) ;


                }else{

                    updateScoreStudentScore() ;

                }


            } else {

                alert(result.error);

            }

        } catch (e) {

        }
    }

}

function updateScoreStudentScore(){

    var courseID = document.update_score_form.course_name.value ;
    var userID = document.update_score_form.student_name.value ;

    if( userID == 0 ){

        alert("该课程没有该用户") ;
        return ;

    }else{

        var data = {} ;

        data.courseID = courseID ;
        data.userID = userID ;

        data = JSON.stringify(data) ;

        sendPost(data,"query/score" ,updateScoreStudentScoreCallBack ) ;

    }

}

function updateScoreStudentScoreCallBack(){

    if (window.jsonHttp.readyState==4 && jsonHttp.status==200) {

        var result;

        try {

            result = JSON.parse(window.jsonHttp.responseText);



            if (result.succes == true) {

                if( result.param.score_list == null ){

                    document.update_score_form.performance.value = "暂无";
                    document.update_score_form.midterm.value = "暂无";
                    document.update_score_form.finals.value = "暂无";
                    document.update_score_form.overall.value = "暂无";

                }else{

                    document.update_score_form.performance.value = result.param.score_list.performance;
                    document.update_score_form.midterm.value = result.param.score_list.midterm;;
                    document.update_score_form.finals.value = result.param.score_list.finals;
                    document.update_score_form.overall.value = result.param.score_list.overall;

                }


            } else {

                alert(result.error);

            }

        } catch (e) {

        }
    }

}

function updateStudentScore(){

    var courseID = document.update_score_form.course_name.value ;
    var userID = document.update_score_form.student_name.value ;


    if( userID == "无"){

        alert("该课程没有学生") ;
        return ;

    }

    var performance = document.update_score_form.performance.value ;
    var midterm = document.update_score_form.midterm.value ;
    var finals = document.update_score_form.finals.value ;
    var overall = document.update_score_form.overall.value ;

    if( performance == "暂无"){

        performance = 0 ;

    }
    if( midterm == "暂无"){

        midterm = 0 ;

    }
    if( finals == "暂无"){

        finals = 0 ;

    }
    if( overall == "暂无"){

        overall = 0 ;

    }

    var  data = {} ;

    var scoresDo = {} ;

    scoresDo.courseID = courseID ;
    scoresDo.userID  = userID ;

    var scoreInfoDo = {} ;

    scoreInfoDo.performance = performance ;
    scoreInfoDo.midterm = midterm ;
    scoreInfoDo.finals = finals ;
    scoreInfoDo.overall = overall ;

    data.scoresDo = scoresDo ;
    data.scoreInfoDo = scoreInfoDo ;

    data = JSON.stringify(data) ;

    sendPost(data,"modify/score",updateStudentScoreCallBack) ;

}

function updateStudentScoreCallBack(){

    if (window.jsonHttp.readyState==4 && jsonHttp.status==200) {

        var result;

        try {

            result = JSON.parse(window.jsonHttp.responseText);

            if (result.succes == true) {

                alert("修改成绩成功") ;
                addRightPage('user_course_table.html' , showTeacherStudentTable ) ;

            } else {

                alert(result.error);

            }

        } catch (e) {

        }
    }

}

//TODO
// Admin dispatch courses for students.
function adminDispatchCourses() {
    document.getElementById("left_page").innerHTML = window.leftPge;
    sendPost(null , "query/course/list" , adminDispatchCoursesFetchCourseListCallback );
}

function courseSelectToggle() {
    var courseSelectList = document.getElementById("course_list");

    var selectedCourse = courseSelectList.options[courseSelectList.selectedIndex].text;
    selectedCourseInfoDo = courseInfoDo_list[courseSelectList.selectedIndex - 1];
    sendPost(selectedCourse, "query/course/teacher", adminDispatchCoursesFetchTeacherListCallback );
}

function adminDispatchCoursesFetchCourseListCallback() {
    var courseSelectList = document.getElementById("course_list");

    if (window.jsonHttp.readyState==4 && jsonHttp.status==200) {

        var result;

        try {

            result = JSON.parse(window.jsonHttp.responseText);
            courseInfoDo_list = result.param.course_list;

            if (result.succes == true) {

                while (courseSelectList.options.length > 1) {
                    courseSelectList.remove(1);
                }
                for (var i = 0;i < courseInfoDo_list.length;i ++) {
                    courseSelectList.options[courseSelectList.options.length] =
                        new Option(courseInfoDo_list[i].name, i);
                }

            } else {

                alert(result.error);

            }

        } catch (e) {

        }
    }
}

function teacherSelectToggle() {
    var teacherSelectList = document.getElementById("teacher_list");
    var selectedTeacher = teacherSelectList.options[teacherSelectList.selectedIndex].value;
    sendPost(null, "query/student_list", adminDispatchCoursesFetchStudentListCallback);
}

function adminDispatchCoursesFetchTeacherListCallback() {
    var teacherSelectList = document.getElementById("teacher_list");

    if (window.jsonHttp.readyState == 4 && window.jsonHttp.status == 200) {
        try {
            var result = JSON.parse(window.jsonHttp.responseText);

            if (result.succes == true) {

                while (teacherSelectList.options.length > 1) {
                    teacherSelectList.remove(1);
                }
                for (var i = 0;i < result.param.teacher_list_on_course.length;i ++) {
                    teacherSelectList.options[teacherSelectList.options.length] =
                        new Option(result.param.teacher_list_on_course[i], i);
                }

            } else {
                alert(result.error);
            }
        } catch (e) {
        }
    }
}

function adminDispatchCoursesFetchStudentListCallback() {
    if (window.jsonHttp.readyState==4 && jsonHttp.status==200) {

        var result;

        try {

            result = JSON.parse(window.jsonHttp.responseText);
            student_list = result.param.student_list;

            if (result.succes == true) {

                student_list_table = document.getElementById("student_info_table");

                for( var i = 1 ; i < student_list.length ; i ++) {

                    student_list_table.rows[i].cells[0].innerHTML = i;
                    student_list_table.rows[i].cells[1].innerHTML = student_list[i].name;
                    student_list_table.rows[i].cells[2].innerHTML = "<input id=\"checkbox" + i + "\" type=\"checkbox\"/>select";
                }

            } else {

                alert(result.error);

            }

        } catch (e) {

        }
    }
}

function adminDispatchCoursesFeedBack() {
    if (window.jsonHttp.readyState == 4 && jsonHttp.status == 200) {
        try {
            var result = JSON.parse(window.jsonHttp.responseText);
            
            if (result.succes == true) {
                alert("Dispatch succeed!")
            } else {
                alert(result.error);
            }
        } catch (e) {

        }
    }
}

function adminDispatchCoursesSubmit() {
    var data = {};
    var student_ids = [];

    data.courseInfoDo = selectedCourseInfoDo;
    for (var i = 1;i < student_list.length;i ++) {
        if (document.getElementById("checkbox" + i).checked) {
            student_ids.push(student_list[i].id);
        }
    }
    data.students = student_ids;

    data = JSON.stringify(data) ;

    sendPost(data, "course/register", adminDispatchCoursesFeedBack);
}
